package com.fy.common.spring.config;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * @author huangming
 * @date 2021/4/1 21:15
 */
@Configuration
public class RestTemplateConfig {
    @Autowired
    private HttpClientPoolConfig httpClientPoolConfig;

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    /**
     * 请求工厂配置
     *
     * @return
     */
    @Bean
    public HttpComponentsClientHttpRequestFactory clientHttpRequestFactory() {
        return new HttpComponentsClientHttpRequestFactory(HttpClients.custom()
                // 使用系统属性
                .useSystemProperties()
                // 最大连接数
                .setMaxConnTotal(httpClientPoolConfig.getMaxConnTotal())
                // 每个路由最大连接数
                .setMaxConnPerRoute(httpClientPoolConfig.getMaxConnectPerRoute())
                // 请求配置
                .setDefaultRequestConfig(requestConfig())
                .build());
    }

    /**
     * 请求配置
     *
     * @return
     */
    private RequestConfig requestConfig() {
        return RequestConfig.custom()
                // 从连接池获取连接超时时间5秒
                .setConnectionRequestTimeout(httpClientPoolConfig.getConnectionRequestTimout())
                // 建立请求连接超时时间10秒
                .setConnectTimeout(httpClientPoolConfig.getConnectTimeout())
                // 等待响应超时时间20秒
                .setSocketTimeout(httpClientPoolConfig.getReadTimeout())
                // 从连接池获取连接的timeout,不宜过大,ms
                .setConnectionRequestTimeout(httpClientPoolConfig.getConnectionRequestTimout())
                .build();
    }

}
